package Lock锁;
/*
Lock锁提供了锁和释放锁的方法
     void Lock():获得锁
     void unlock():释放锁

Lock是接口不能被实例化，这里采用他的实现类RentrantLock来实例化
     ReentrantLock ():创建一个ReentrantLock的实例
 */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
    private int tickets = 100;
    //创建Lock锁对象
    private Lock lock = new ReentrantLock();

    public void run() {
        while (true) {
            //try...finally块实现锁以防代码中出现问题
            try {
                lock.lock();//加锁
                if (tickets > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                    tickets--;
                }
            } finally {
                lock.unlock();//释放锁
            }
        }
    }
}